package com.action.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.action.childbase.ChildBaseActivity;
import com.action.entity.CommonBean;
import com.action.entity.UserCommentVO;
import com.action.entity.XyBUserRecvRed;
import com.action.entity.event.RedPacketChangeEvent;
import com.action.service.pressenter.RedpakcetPressenter;
import com.action.ui.adapter.ShowImageAdapter;
import com.action.utils.GridDividerItemDecoration;
import com.action.utils.SingleClick;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.base.app_core.View.XRecyclerView;
import com.base.app_core.View.xrecyclerview.RecyclerAdapter;
import com.base.app_core.View.xrecyclerview.RecyclerViewHolder;
import com.base.app_core.base.ActionPacketView;
import com.base.app_core.model.Paginated;
import com.base.app_core.model.dto.Advertiser;
import com.base.app_core.service.user.model.HomeRxBean;
import com.base.app_core.service.user.model.User;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.Preferences;
import com.base.app_core.util.XYBAUtils;
import com.blankj.utilcode.util.StringUtils;
import com.hwangjr.rxbus.RxBus;
import com.luseen.autolinklibrary.AutoLinkMode;
import com.luseen.autolinklibrary.AutoLinkTextView;
import com.tencent.map.lib.util.StringUtil;
import com.xinglai.yun.Application;
import com.xinglai.yun.R;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;

//红包详情
@Route(path = AppConstants.ROUTEURI.BASE_AD_VIEW)
public class AdRedPacketDetail extends ChildBaseActivity<RedpakcetPressenter> implements
        ActionPacketView.RedPacketAction, ActionPacketView.onPostComment,ShowImageAdapter.onDefaultImageAddLisener {

    private static final int IMAGE = 0;
    private static final int TEXT = 1;
    @Inject
    User user;

    String sn;

    ImageView redpacketSenderImg;

    RecyclerView imgContainer;
    ViewStub signalImg;

    ViewStub moreImgs;
    ViewStub adCooration;
    AutoLinkTextView redContent;

    private ShowImageAdapter addImageAdapter;

    TextView redRecvPrice;

    TextView dan;

    TextView redGufenPrice;

    @BindView(R.id.close_category_list)
    ImageView closeIv;

    @BindView(R.id.text_close)
    TextView closeTv;

    LinearLayout mAdDetail;

    @BindView(R.id.adview)
    XRecyclerView xRecyclerView;

    @BindView(R.id.et_commemnt)
    EditText etCommemnt;

    @BindView(R.id.post_comment)
    TextView mPostComment;

    private XyBUserRecvRed redpacket;

    private boolean fromOpen;

    private RedUserCommentAdapter redUserCommentAdapter;

    private int pageNo = 1;

    private TextView senderHint;

    private TextView mCommentCount;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_red_packet_ad_detail;
    }

    @Override
    protected void initView() {
        super.initView();
        Application.getAdViewNativeManager().init(((Application) getApplication()).getAdViewInit(), new String[]{AppConstants.adview_sdk_key});
        Application.getAdViewBannerManager().init(((Application) getApplication()).getAdViewInit(), new String[]{AppConstants.adview_sdk_key});
        sn = getIntent().getStringExtra("sn");
        fromOpen = getIntent().getBooleanExtra("fromOpen", true);
        if (StringUtils.isEmpty(sn)) {
            finish();
            return;
        }

        if (fromOpen) {
            setSwipeBackEnable(false);
        }

        initTypeView();
        setToolBar("红包信息");
        showProgress();
        requestNativeRequest();
        etCommemnt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    mPostComment.setVisibility(View.VISIBLE);
                } else {
                    if (StringUtil.isEmpty(etCommemnt.getText().toString())) {
                        mPostComment.setVisibility(View.GONE);
                    }
                }
            }
        });
        imgContainer = (RecyclerView) moreImgs.inflate();
        addImageAdapter = new ShowImageAdapter();
        addImageAdapter.setOnDefaultImageAddLisener(this);
        addImageAdapter.setShowDeleteButton(false);
        GridLayoutManager layout = new GridLayoutManager(this, 3);
        imgContainer.setLayoutManager(layout);
        imgContainer.addItemDecoration(new GridDividerItemDecoration(XYBAUtils.dip2px(8), getResources().getColor(R.color.white)));
        imgContainer.setAdapter(addImageAdapter);
        redContent.addAutoLinkMode(AutoLinkMode.MODE_URL);
        redContent.setUrlModeColor(ContextCompat.getColor(this, R.color.green));
        redContent.enableUnderLine();
        mPresenter.notifyInvalidCorrent();
    }


    private void fillerOtherAdNative() {
        fillAllEmptyView();
    }

    private void requestNativeRequest() {
        fillerOtherAdNative();
    }


    private void fillAllEmptyView() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                requestPageClose();
                mPresenter.indexGetAdvertiseInfo(AppConstants.Const.MI_TYPE);
            }
        });
    }

    List<CommonBean> mArr = new ArrayList<CommonBean>();

    /**
     * 初始化红包类型的view
     */
    private void initTypeView() {
        View inflate = getLayoutInflater().inflate(R.layout.item_header_ad_layout, null);
        redpacketSenderImg = ButterKnife.findById(inflate, R.id.redpacket_sender_img);
        senderHint = ButterKnife.findById(inflate, R.id.sender_hint);
        redRecvPrice = ButterKnife.findById(inflate, R.id.red_recv_price);
        dan = ButterKnife.findById(inflate, R.id.dan);
        redGufenPrice = ButterKnife.findById(inflate, R.id.red_gufen_price);
        mAdDetail = ButterKnife.findById(inflate, R.id.ad_detail);
        mCommentCount = ButterKnife.findById(inflate, R.id.comment_count);
        signalImg=ButterKnife.findById(inflate,R.id.signal_img);
        moreImgs=ButterKnife.findById(inflate,R.id.more_imgs);
        adCooration=ButterKnife.findById(inflate,R.id.ad_cooration);
        redContent=ButterKnife.findById(inflate,R.id.red_content);
        xRecyclerView.setLayoutManager(new LinearLayoutManager(AdRedPacketDetail.this, LinearLayoutManager.VERTICAL, false));
        xRecyclerView.setPullRefreshEnabled(false);
        xRecyclerView.setLoadingMoreEnabled(true);
        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                pageNo += 1;
                fetchCommentList();
            }
        });
        xRecyclerView.addHeaderView(inflate);
        try {
            if (fromOpen) {
                closeTv.setText(String.valueOf(AppConstants.DEFAULT_AD_TIME));
                closeTv.setVisibility(View.VISIBLE);
                closeIv.setVisibility(View.GONE);
            } else {
                closeTv.setVisibility(View.GONE);
                closeIv.setVisibility(View.VISIBLE);
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                redpacketSenderImg.setBackground(getResources().getDrawable(R.drawable.shape_circle_stock));
            }
            redUserCommentAdapter = new RedUserCommentAdapter();
            xRecyclerView.setAdapter(redUserCommentAdapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        pageNo = 1;
        fetchRedpacketDetail();
        fetchCommentList();
    }

    public void fetchCommentList() {
        if (null != mPresenter) {
            mPresenter.fetchCommentList(sn, pageNo);
        }
    }

    private void fetchRedpacketDetail() {
        if (!StringUtils.isEmpty(sn) && null != mPresenter) {
            mPresenter.fetchRedpacketDetail(sn);
        }
    }

    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(AdRedPacketDetail.this);
    }
    List<Advertiser> advertiserList=null;
    ImageView adIv=null;
    TextView adTv=null;
    TextView title=null;
    TextView ad_source=null;
    View convertView=null;
    private void showAd(){
        if(redpacket==null)
            return;
        if(redpacket.getSenderId()!=-1)
            return;

        if(advertiserList==null||advertiserList.size()<=0)
            return;
        Random random = new Random();
        Advertiser advertiser = advertiserList.get(random.nextInt(advertiserList.size()));
        final String url = advertiser.getUrl();
        String img = advertiser.getImg();
        String name = advertiser.getName();

        Preferences.putString(AppConstants.SP.ADVERTISE_URL, url);
        Preferences.putString(AppConstants.SP.ADVERTISE_IMG, img);
        String logo = advertiser.getLogo();
        if (!StringUtils.isEmpty(logo)) {
            XYBAUtils.displayCircleImage(AdRedPacketDetail.this, logo, redpacketSenderImg);
        }

        final CommonBean e = new CommonBean();
        e.setDis(name);
        e.setImgs(img);
        String adContent = advertiser.getAdContent();
        if (StringUtils.isEmpty(adContent)) {
            e.setDis("平台发赏金了");
        } else {
            e.setDis(adContent);
        }

        if (StringUtils.isEmpty(name)) {
            e.setTitleStr("推广");
        } else {
            e.setTitleStr(name);
        }
        e.setAdSource(null);
        e.setSourceType(TEXT);
        e.setTitleType(TEXT);
        e.setUrl(url);
        e.setAdType(CommonBean.DEFAULT);
        if(adIv==null){
            convertView=adCooration.inflate();
            if(convertView!=null) {
                adIv = ButterKnife.findById(convertView, R.id.ad_iv);
                ViewGroup.LayoutParams layoutParams = adIv.getLayoutParams();
                layoutParams.height = XYBAUtils.getWindowWidth() * 7 / 18;
                adIv.setLayoutParams(layoutParams);
                adTv = convertView.findViewById(R.id.ad_text);
                title = convertView.findViewById(R.id.title);
                ad_source = convertView.findViewById(R.id.ad_source);
            }
        }
        XYBAUtils.displayImage(e.getImgs(),adIv);
        adTv.setText(e.getTitleStr());
        title.setText(e.getTitleStr());
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = e.getUrl();
                if (StringUtils.isEmpty(url)) {
                    return;
                }

                if (XYBAUtils.checkAliApkExist(AdRedPacketDetail.this)) {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    showToast("请安装支付宝");
                }
            }
        });
    }
    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        super.notifyData(object, tClass, paginated);
        if (object instanceof Collection) {
            if (tClass == UserCommentVO.class) {
                List<UserCommentVO> o = (List<UserCommentVO>) object;
                if (redUserCommentAdapter == null || xRecyclerView == null) {
                    return;
                }
                if (pageNo == 1) {
                    redUserCommentAdapter.clear();
                }

                redUserCommentAdapter.addAll(o);
                redUserCommentAdapter.notifyDataSetChanged();
                if (redUserCommentAdapter != null) {
                    xRecyclerView.setLoadingMoreEnabled(paginated.getHasMore());
                }
            } else if (tClass == Advertiser.class) {
                dismissProgress();
                advertiserList = (List<Advertiser>) object;
                if (XYBAUtils.isEmpty(advertiserList)) {
                    return;
                }
                showAd();

            }
        } else if (object instanceof XyBUserRecvRed) {//红包详情
            redpacket = (XyBUserRecvRed) object;
            XYBAUtils.displayCircleImage(AdRedPacketDetail.this, redpacket.getWxIcon(), redpacketSenderImg);
            String userPrice = redpacket.getUserPrice();
            if (StringUtils.isEmpty(userPrice)) {
                redRecvPrice.setVisibility(View.GONE);
                dan.setVisibility(View.GONE);
            } else {
                redRecvPrice.setText(new BigDecimal(userPrice).setScale(4, BigDecimal.ROUND_DOWN).toPlainString());
                redRecvPrice.setVisibility(View.VISIBLE);
                dan.setVisibility(View.VISIBLE);
            }
            String senderName=StringUtils.isEmpty(redpacket.getWxNickname())?StringUtils.isEmpty(redpacket.getSenderNickname())?"全城红包":redpacket.getSenderNickname():redpacket.getWxNickname();
            senderHint.setText(senderName);
            mCommentCount.setText(redpacket.getCommentCount() == 0 ? "评价" : "评价(" + redpacket.getCommentCount() + ")");
            if(redpacket.getSenderId()!=-1&&!StringUtils.isEmpty(redpacket.getContent()))
                redContent.setAutoLinkText(redpacket.getContent());
            else
                redContent.setVisibility(View.GONE);
            String stockCount = redpacket.getStockCount();
            if (StringUtils.isEmpty(stockCount)) {
                redGufenPrice.setVisibility(View.GONE);
            } else {
                redGufenPrice.setVisibility(View.VISIBLE);
                redGufenPrice.setText("+" + stockCount + "红包股");
            }
//            if (redpacket.getRange() > 0) {
//                tvRange.setText(redpacket.getRange() / 1000 + "km");
//            } else if (redpacket.getRange() == 0) {
//                tvRange.setText("全区");
//            } else if (redpacket.getRange() == -1) {
//                tvRange.setText("全市");
//            } else if (redpacket.getRange() == -2) {
//                tvRange.setText("全省");
//            } else if (redpacket.getRange() == -3) {
//                tvRange.setText("全国");
//            }
                if(redpacket.getSenderId()!=-1) {
                    String imgs = redpacket.getImgs();
                    if (!StringUtil.isEmpty(imgs)) {
                        if (imgs.contains(",")) {
                            List<String> split = Arrays.asList(imgs.split(","));
                            if (!XYBAUtils.isEmpty(split)) {
                                addImageAdapter.notifyDataSetChanged(split);
                            }
                        } else {
                            ImageView singImg = signalImg.inflate().findViewById(R.id.img_container);
                            ViewGroup.LayoutParams layoutParams = singImg.getLayoutParams();
                            layoutParams.width = XYBAUtils.getScreenWidth() - XYBAUtils.dip2px(16) * 2;
                            layoutParams.height = XYBAUtils.getScreenWidth() - XYBAUtils.dip2px(16) * 2;
                            singImg.setLayoutParams(layoutParams);
                            XYBAUtils.displayImage(imgs, singImg);
                            singImg.setVisibility(View.VISIBLE);
                            singImg.setClickable(true);
                        }
                        imgContainer.setVisibility(View.VISIBLE);
                    } else {
                        imgContainer.setVisibility(View.GONE);
                    }
                }else{//广告红包
                    showAd();
                }
            if (fromOpen && redpacket != null) {
                RedPacketChangeEvent event = new RedPacketChangeEvent();
                event.setRedpacket(redpacket);
                event.setStatus(RedPacketChangeEvent.PACKET_ROBED);
                RxBus.get().post(new HomeRxBean(HomeRxBean.SEND_REDPACKET, event));
            }

        }
    }


    @Override
    public void notifyError(String errorCode, String content) {
        super.notifyError(errorCode, content);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        long timeOutCount = mPresenter.getmTick();
        if (fromOpen && timeOutCount > 0) {
            showToast("请观看片刻");
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void updateCloseView(int tick) {
        closeTv.setText(String.valueOf(tick));
        if (tick <= 0) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    closeIv.setVisibility(View.VISIBLE);
                    closeTv.setVisibility(View.GONE);
                }
            });
        }
    }

    public void requestPageClose() {
        if (fromOpen) {
            mPresenter.notifyCloseTextChange();
        }
    }


    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm:ss");

    @Override
    public void onCommentSuccess() {
        //评论成功
        dismissProgress();
        UserCommentVO userCommentVO = new UserCommentVO();
        userCommentVO.setComment(etCommemnt.getText().toString());
        userCommentVO.setCommentTime(simpleDateFormat.format(new Date()));
        userCommentVO.setRedpacketSn(redpacket.getSn());
        userCommentVO.setUserId(user.getId());
        userCommentVO.setWxIcon(user.getWxIcon());
        userCommentVO.setWxNickname(user.getWxNickname());
        redUserCommentAdapter.getList().add(userCommentVO);
        redUserCommentAdapter.notifyDataSetChanged();
        etCommemnt.setText("");
        mPostComment.setVisibility(View.INVISIBLE);
        etCommemnt.clearFocus();
    }

    @Override
    public void onClickAction(boolean isNoEmpty, String item) {
        if (isNoEmpty) {
            addImageAdapter.previewImage(this, item);
        } else {
            PhotoPicker.builder()
                    .setPhotoCount(1)
                    .setShowCamera(true)
                    .setShowGif(false)
                    .setPreviewEnabled(true)
                    .setShowCamera(true)
                    .start(this, PhotoPicker.REQUEST_CODE);
        }
    }

    public static class RedUserCommentAdapter extends RecyclerAdapter<UserCommentVO, RedUserCommentAdapter.ViewHolder> {

        @Override
        protected void fillData(UserCommentVO item, ViewHolder holder) {
            XYBAUtils.displayCircleImage(holder.itemView.getContext(), item.getWxIcon(), holder.userImage);
            holder.commentName.setText(item.getWxNickname());
            holder.commentContent.setText(item.getComment());
            holder.commentDate.setText(item.getCommentTime());
        }

        @Override
        protected int getItemLayoutId() {
            return R.layout.unit_user_comment_redpacket;
        }

        public class ViewHolder extends RecyclerViewHolder {
            @BindView(R.id.user_image)
            ImageView userImage;
            @BindView(R.id.comment_name)
            TextView commentName;
            @BindView(R.id.comment_content)
            TextView commentContent;
            @BindView(R.id.comment_date)
            TextView commentDate;

            public ViewHolder(View itemView) {
                super(itemView);
            }
        }
    }

    @OnClick(R.id.post_comment)
    public void onClickPostComment() {
        if (SingleClick.isSingle()) {
            showProgress();
            String comment = etCommemnt.getText().toString();
            if (StringUtil.isEmpty(comment)) {
                showToast("请输入评论内容");
                return;
            }

            if (null != mPresenter) {
                showProgress();
                mPresenter.postComment(comment, sn);
            }
            hideInputSoft(etCommemnt);
        }
    }
}
